package com.ms.p2p.template.directive;


import com.ms.common.utils.FreemarkerUtils;
import freemarker.core.Environment;
import freemarker.template.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public abstract class BaseDirective implements TemplateDirectiveModel {

	/**
	 * 输出参数：列表数据
	 */
	public static final String OUT_LIST = "tag_list";

	private static final String UseCache = "useCache";
	private static final String ID = "id";
	private static final String COUNT = "count";

	protected boolean getUseCache(Environment environment, Map map) throws TemplateModelException {
		Boolean useCache = (Boolean) FreemarkerUtils.getParameter(UseCache, Boolean.class, map);
		return useCache != null && useCache;
	}
	
	protected Long getId(Map map) throws TemplateModelException {
		return (Long)FreemarkerUtils.getParameter(ID, Long.class, map);
	}

	protected Integer getCount(Map map) throws TemplateModelException {
		return (Integer)FreemarkerUtils.getParameter(COUNT, Integer.class, map);
	}

	protected void renderParamToBody(Map map, Environment environment,
			TemplateDirectiveBody templatedirectivebody) throws TemplateException, IOException {
		HashMap<String, Object> hashmap = new HashMap<>();

		for (Object obj : map.keySet()) {
			String s = (String)obj;
			hashmap.put(s, FreemarkerUtils.getVariable(s, environment));
		}

		FreemarkerUtils.setVariables(map, environment);
		templatedirectivebody.render(environment.getOut());
		FreemarkerUtils.setVariables(hashmap, environment);
	}
	/**
	 * 设置局部变量
	 *
	 * @param name
	 *            名称
	 * @param value
	 *            变量值
	 * @param env
	 *            Environment
	 * @param body
	 *            TemplateDirectiveBody
	 */
	protected void setLocalVariable(String name, Object value, Environment env, TemplateDirectiveBody body) throws TemplateException, IOException {
		TemplateModel sourceVariable = FreemarkerUtils.getVariable(name, env);
		FreemarkerUtils.setVariable(name, value, env);
		body.render(env.getOut());
		FreemarkerUtils.setVariable(name, sourceVariable, env);
	}
	protected void renderParamToBody(String s, Object obj, Environment environment, TemplateDirectiveBody templatedirectivebody) {
		TemplateModel templatemodel;
		try {
			templatemodel = FreemarkerUtils.getVariable(s, environment);
			FreemarkerUtils.setVariable(s, obj, environment);
			templatedirectivebody.render(environment.getOut());
			FreemarkerUtils.setVariable(s, templatemodel, environment);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
